<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Created by PhpStorm.
 * Author: ljb
 * Desc: 12301合同处理
 */
class Controller_Admin_Dispose extends Stourweb_Controller
{
    private $secretId = 'AKIDekwdCbS7Lb3yqPEaUw5uqVYkagrgoCtMnd32';
    private $secretKey = 'f0t6chnuCxF7Yjfou5o29L5dqiD88P9pOivkcPzw';
    private $apiUrl = 'http://api.stccs.com.cn/e12301/api';
    private $partnerId = '';//测试id：114991817783428586644806444
    private $result;

    private $status = array(
        array('id' => 1, 'name' => '已生成'),
        array('id' => 2, 'name' => '已签署'),
        array('id' => 3, 'name' => '已作废'),
        array('id' => 4, 'name' => '签署中,部分人员未签署'),// [已签订申请作废]
        array('id' => 5, 'name' => '作废中,部分人员未作废')
    );

    function before()
    {
        parent::before();
        $this->result = array(
            'status' => true,//默认状态为成功
            'msg' => '操作成功',//默认的提示消息
            'data' => array()
        );
        $this->assign('party', Model_Contract::get_contract_config());
        $this->assign('models', Model_Contract::get_opentypes());
        $party_defalut = Model_Sysconfig::get_configs(0, 'cfg_default_partyB', 1);
        $this->assign('default_partyB', $party_defalut ? $party_defalut : 0);
        //获得12301合同partnerid
        $partnerId = Model_Sysconfig::get_sys_conf('value', 'cfg_contract_partnerid', 0);
        $this->partnerId = $partnerId;
    }

    public function request($data, $type)
    {
        $header = $this->generateHeader($this->apiUrl);
        $rtn = $this->http($this->apiUrl, $data, $header, $type);
        return $rtn;
    }

    /**
     * 生成header
     * @param $uri
     * @return array
     */
    private function generateHeader($uri)
    {
        date_default_timezone_set('GMT');
        $date = gmdate("D, d M Y H:i:s T");
        date_default_timezone_set('PRC');
        $authorization = $this->buildSign($uri, $date);
        $header = array(
            /*  'Host: '.$uri, // 用户 API 所在服务的域名
              'Accept: text/html',*/
            'Uri: ' . $uri,
            'Date: ' . $date,
            'Authorization: ' . $authorization,
            //'X-Requested-With: XMLHttpRequest'
            //'Accept-Encoding: gzip, deflate, sdch'

        );
        return $header;

    }

    private function http($url, $data, $header, $type = 'post')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $rtn = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        }
        curl_close($ch);
        if ($this->isJson($rtn)) {
            return json_decode($rtn, true);
        } else {
            return $rtn;
        }
    }

    //判断是否为json
    private function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }


    private function validSign()
    {
        //todo sign 验证

        if ($_SERVER['HTTP_AUTHORIZATION'] != self::buildSign($_SERVER['REQUEST_URI'], $_SERVER['HTTP_DATE'])) {
            self::outputError('BA验证错误');
        }
        return true;
    }

    //生成签名
    private function buildSign($uri, $date)
    {
        $srcStr = "date: " . $date . "\n" . "uri: " . $uri;
        $signStr = base64_encode(hash_hmac('sha1', $srcStr, $this->secretKey, true));
        $authorization = 'hmac id="' . $this->secretId . '", algorithm="hmac-sha1", headers="date uri", signature="';
        $authorization = $authorization . $signStr . "\"";
        return $authorization;


    }

    //合同列表
    public function action_get_list()
    {
        $action = $this->params['action'];
        if (!$action) {
            $this->display('admin/dispose/list');
        }
        if ($action == 'read') {
            $start = $_GET['start'];
            $limit = $_GET['limit'];
            $keyword = $_GET['keyword'];
            $typeid = $_GET['typeid'];
            $where = 'sline_contract_supervise.id >0';
            if ($keyword) {
                $where .= " and sline_contract_supervise.contractnName like '%$keyword%'";
            }
            if ($typeid) {
                $where .= " and sline_contract_supervise.typeid=$typeid";
            }

            $sort = json_decode($_GET['sort'], true);
            $sort = $sort[0];
            if ($sort) {
                $property = $sort['property'];
                $direction = $sort['direction'];
            } else {
                $property = 'id';
                $direction = 'desc';
            }

            $total = DB::select(DB::expr('count(`sline_contract_supervise`.`id`) as num'))->from('contract_supervise')
                ->join('member_order', 'LEFT')->on('contract_supervise.order_id', '=', DB::expr('`sline_member_order`.id'))
                ->where($where)->where('member_order.status', 'not in', [3,4])->execute()->get('num');
            $list = DB::select('contract_supervise.*')->from('contract_supervise')
                ->join('member_order', 'LEFT')->on('contract_supervise.order_id', '=', DB::expr('`sline_member_order`.id'))
                ->where($where)->where('member_order.status', 'not in', [3,4])
                ->offset($start)->limit($limit)->group_by('contract_supervise.order_id')->order_by($property, $direction)->execute()->as_array();
            foreach ($list as &$l) {
                if ($l['typeid']) {
                    $l['typename'] = DB::select('shortname')->from('nav')
                        ->where('typeid', '=', $l['typeid'])->execute()->get('shortname');
                } else {
                    $l['typename'] = '未设置';
                }
                $ordersn=DB::select('ordersn')->from('member_order')->where('id','=',$l['order_id'])->execute()->current();
                $l['ordersn']=$ordersn['ordersn'];
            }
            unset($l);
            echo json_encode(array('total' => $total, 'list' => $list));
        } elseif ($action == 'update') {
            $id = $_POST['id'];
            $val = $_POST['val'];
            $field = $_POST['field'];
            DB::update('contract_supervise')->set(array($field => $val))->where('id', '=', $id)->execute();
            echo 'ok';
        } elseif ($action == 'delete') {
            $data = file_get_contents('php://input');
            $data = json_decode($data);
            if ($data->id) {
                DB::delete('contract_supervise')->where('id', '=', $data->id)->execute();
            }
        }
    }

    //添加/修改合同
    public function action_add()
    {
        $id = $this->params['id'];
        if ($id) {
            $info = DB::select()->from('contract_supervise')
                ->where('id', '=', $id)->execute()
                ->current();
            foreach ($info as $key => $vel) {
                if (!is_null(json_decode($vel, true))) {
                    $info[$key] = json_decode($vel, true);
                }
            }
            $this->assign('info', $info);
        } else {
            $this->assign('info', '');
        }
        $this->display('admin/dispose/add');
    }

    //添加修改合同数据提交
    public function action_add_ajax()
    {
        $data = $_POST;
        $id = $_POST['id'];
        $updata = array();
        $updata['contractnName'] = $data['title'];
        $updata['typeid'] = $data['typeid'];
        $updata['status'] = 0;
        $updata['templateId'] = $data['templateId'];
        $updata['stamp'] = $data['stamp'];
        $updata['isMultiSignatory'] = $data['isMultiSignatory'];
        $updata['supplementaryClause'] = $data['supplementaryClause'];
        //签约社
        $updata['travelAgency']['transactorName'] = $data['transactorName'];
        $updata['travelAgency']['transactorPhone'] = $data['transactorPhone'];
        $updata['travelAgency']['localComplaintPhone'] = Model_Sysconfig::get_sys_conf('value', 'cfg_contract_localComplaintPhone',0);//旅游投诉服务热线
        $updata['travelAgency']['agencyName'] = $data['agencyName'];
        $updata['travelAgency']['travelAgencyLicenseNumber'] = $data['travelAgencyLicenseNumber'];
        $updata['travelAgency']['businessLicenseNumber'] = $data['businessLicenseNumber'];
        //签署人/游客代表
        $updata['signatory']['mode'] = $data['mode'];
        $updata['signatory']['name'] = $data['signatory_name'];
        $updata['signatory']['ID'] = array();
        $updata['signatory']['ID']['IDType'] = $data['signatory_IDType'];
        $updata['signatory']['ID']['IDNumber'] = $data['signatory_IDNumber'];
        $updata['signatory']['phone'] = $data['signatory_phone'];
        //解决争议部分
        $updata['dispute']['resolution'] = $data['resolution'];
        $updata['dispute']['tribunalName'] = $data['tribunalName'];
        $updata['dispute']['courtName'] = $data['courtName'];
        //成团约定部分
        $updata['groupAgreement']['resolution'] = $data['groupAgreement_resolution'];
        $updata['groupAgreement']['leastCustomerNumber'] = $data['leastCustomerNumber'];
        $updata['groupAgreement']['agreeToTransfer'] = $data['agreeToTransfer'];
        $updata['groupAgreement']['agreeToDelay'] = $data['agreeToDelay'];
        $updata['groupAgreement']['agreeToChangeLine'] = $data['agreeToChangeLine'];
        $updata['groupAgreement']['agreeToTerminate'] = $data['agreeToTerminate'];
        $updata['groupAgreement']['agreeToMerge'] = $data['agreeToMerge'];
        $updata['groupAgreement']['transferToCompanyName'] = $data['transferToCompanyName'];
        $updata['groupAgreement']['mergeToCompanyName'] = $data['mergeToCompanyName'];
        //导游部分
        $gui = array();
        $gui['name'] = $data['tourGuides_name'];
        $gui['phone'] = $data['tourGuides_phone'];
        $gui['tourGuideID'] = $data['tourGuideID'];
        $updata['tourGuides'] = array($gui);
        //行程部分
        $updata['itinerary']['inputType'] = $data['inputType'];
        $updata['itinerary']['startDate'] = $data['startDate'];
        $updata['itinerary']['days'] = $data['days'];
        $updata['itinerary']['nights'] = $data['nights'];
        $updata['itinerary']['routeName'] = $data['routeName'];
        //费用部分
        $updata['cost']['adultCost'] = $data['adultCost'];
        $updata['cost']['childCost'] = $data['childCost'];
        $updata['cost']['singleSupplementCost'] = $data['singleSupplementCost'];
        $updata['cost']['totalCost'] = $data['totalCost'];
        $updata['cost']['paymentMethod'] = $data['paymentMethod'];
        //保险部分
        $updata['insurance']['purchaseMethod'] = $data['purchaseMethod'];
        $updata['insurance']['productName'] = $data['productName'];
        $updata['insurance']['company'] = $data['company'];
        //自费项目部分
        $updata['activities']['date'] = $data['date'];
        $updata['activities']['place'] = $data['place'];
        $updata['activities']['item'] = $data['item'];
        $updata['activities']['fee'] = $data['fee'];
        $updata['activities']['stayDuration'] = $data['stayDuration'];
        $updata['activities']['memo'] = $data['memo'];
        //购物部分
        $updata['hasShopping'] = $data['hasShopping'];
        $updata['shoppingViewSpot'] = $data['shoppingViewSpot'];
        $updata['shoppings']['date'] = $data['shoppings_date'];
        $updata['shoppings']['place'] = $data['shoppings_place'];
        $updata['shoppings']['shoppingPlace'] = $data['shoppingPlace'];
        $updata['shoppings']['goods'] = $data['goods'];
        $updata['shoppings']['stayDuration'] = $data['shoppings_stayDuration'];
        $updata['shoppings']['memo'] = $data['shoppings_memo'];
        //游客部分
        $updata['touristsInfo']['totalNumber'] = $data['totalNumber'];
        $updata['touristsInfo']['adultNumber'] = $data['adultNumber'];
        $updata['touristsInfo']['childNumber'] = $data['childNumber'];
        $updata['touristsInfo']['emergencyContactName'] = $data['emergencyContactName'];
        $updata['touristsInfo']['emergencyContactPhone'] = $data['emergencyContactPhone'];
        $updata['callbackURL']=$GLOBALS['cfg_basehost'] .'/contract/get_contract';//接收回调地址
        //游客列表
        $updata['touristsInfo']['tourists'] = array();
        foreach ($data['tourists'] as $key => $vel) {
            $array = array();
            $array['number'] = $vel['number'];
            $array['inputType'] = $vel['inputType'];
            $array['isSigner']=$vel['isSigner'];
            $array['name'] = $vel['name'];
            $array['gender'] = $vel['gender'];
            $array['nationality'] = $vel['nationality'];
            $array['phone'] = $vel['phone'];
            $array['address'] = $vel['address'];
            $array['ID']['IDType'] = $vel['IDType'];
            $array['ID']['IDNumber'] = $vel['IDNumber'];
            array_push($updata['touristsInfo']['tourists'], $array);
        }
        $updata['addtime'] = time();
        foreach ($updata as $key => $vel) {
            if (is_array($vel)) {
                $updata[$key] = json_encode($vel);
            }
        }
        if (empty($id)) {//新增
            list($id) = DB::insert('contract_supervise', array_keys($updata))->values(array_values($updata))->execute();
        } else {//编辑
            DB::update('contract_supervise')->set($updata)->where('id', '=', $id)->execute();
        }
        echo $id;
    }

    //申报合同
    public function action_reporting_contract()
    {
        $constract_supid = $_POST['id'];
        //获得合同信息
        $supervise = DB::select()->from('contract_supervise')->where('id', '=', $constract_supid)->execute()->current();
        if ($supervise) {
            foreach ($supervise as $key => $vel) {
                if (!is_null(json_decode($vel, true))) {
                    $supervise[$key] = json_decode($vel, true);
                }
            }
            //上传签章
            //$upstemp = $this->uploading_stemp($supervise['stamp'], $supervise['travelAgency']['travelAgencyLicenseNumber']);
            //$upstemp = json_decode($upstemp, true);
            //if ($upstemp['data']['state'] !== 'ok') {
            //    echo json_encode(['status'=>'no','data'=>$upstemp]);
			//	exit;
            //}
            unset($supervise['id']);
            unset($supervise['contract_id']);
            unset($supervise['typeid']);
            unset($supervise['contractnName']);
            unset($supervise['addtime']);
            unset($supervise['status']);
            unset($supervise['partyBid']);
            unset($supervise['apiVersion']);
            unset($supervise['fileURL']);
            unset($supervise['signingURL']);
            unset($supervise['QRCodeURL']);
            $supervise['uri'] = '/v1/econtract/apply';
            $supervise['partnerId'] = $this->partnerId;
            $result = $this->request($supervise, 'post');
            if ($result['data']) {
                //增加合同编号，文件地址等信息
                if ($result['data']['contractNumber']) {
                    $cdata['contractNumber'] = $result['data']['contractNumber'];
                }
                if ($result['apiVersion']) {
                    $cdata['apiVersion'] = $result['apiVersion'];
                }
                if ($result['data']['fileURL']) {
                    $cdata['fileURL'] = $result['data']['fileURL'];
                }
                if ($result['data']['signingURL']) {
                    $cdata['signingURL'] = $result['data']['signingURL'];
                }
                if ($result['data']['QRCodeURL']) {
                    $cdata['QRCodeURL'] = $result['data']['QRCodeURL'];
                }
                if ($result['data']['viewURL']) {
                    $cdata['viewURL'] = $result['data']['viewURL'];
                }
                $cdata['status'] = 1;
                DB::update('contract_supervise')->set($cdata)->where('id', '=', $constract_supid)->execute();
                echo json_encode(['status'=>'ok','data'=>$result]);
				exit;
            } else {
                //获取错误信息
                $msg = isset($result['error']['errors'][0]) ? '申报失败,'.$result['error']['errors'][0]['reason'] : '合同申报失败';
                exit(json_encode(array('status'=>'no','msg'=>$msg,'data'=>$result)));
            }
        } else {
            echo json_encode(['status'=>'no','data'=>'合同信息不存在']);
			exit;
        }
    }

    //预览合同
    public function action_get_view()
    {
        $constract_supid = $_POST['id'];
        //获得合同信息
        $supervise = DB::select('viewURL')->from('contract_supervise')->where('id', '=', $constract_supid)->execute()->current();
        if (!empty($supervise['viewURL'])) {
            $this->result['data'] = array('viewURL' => $supervise['viewURL']);
        } else {
            $this->result['status'] = false;
            $this->result['msg'] = '未申报合同';
        }
        echo json_encode($this->result);
    }

    //下载合同
    public function action_download_contract()
    {
        $constract_supid = $_POST['id'];
        //获得合同信息
        $supervise = DB::select('fileURL')->from('contract_supervise')->where('id', '=', $constract_supid)->execute()->current();
        if (!empty($supervise['fileURL'])) {
            $this->result['data'] = array('fileURL' => $supervise['fileURL']);
        } else {
            $this->result['status'] = false;
            $this->result['msg'] = '未申报合同';
        }
        echo json_encode($this->result);
    }

    //合同作废
    public function action_cancel_contract()
    {
        $constract_supid = $_POST['id'];
        //获得合同信息
        $supervise = DB::select()->from('contract_supervise')->where('id', '=', $constract_supid)->execute()->current();
        $data['uri'] = '/v1/econtract/invalidate/' . $supervise['contractNumber'];
        $data['partnerId'] = $this->partnerId;
        $this->apiUrl = $this->apiUrl . '?uri=' . $data['uri'] . '&partnerId=' . $data['partnerId'];
        $result = $this->request($data, 'post');
        if ($result['data']['state'] == 'ok') {
            $cdata['status'] = 5;
            DB::update('contract_supervise')->set($cdata)->where('id', '=', $supervise['id'])->execute();
        }
        echo json_encode($result);
    }

    //上传签章
    public function uploading_stemp($url, $travelAgencyLicenseNumber)
    {
        //获得图片并把图片转为base64
        $supervise['stamp'] = $this->fileToBase64(BASEPATH . $url);
        $supervise['uri'] = '/v1/econtract/stamp/' . $travelAgencyLicenseNumber;
        $supervise['partnerId'] = $this->partnerId;
        $result = $this->request($supervise, 'post');
        return json_encode($result);
    }

    //将图片进行base64编码
    function fileToBase64($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64 = chunk_split(base64_encode($image_data));
        $base64_image = str_replace("\r\n", "", $base64);
        //$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }


}